package com.yang.flower.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Result;
import com.yang.flower.config.AuthAccess;
import com.yang.flower.entity.Discounts;
import com.yang.flower.service.DiscountsService;
import com.yang.flower.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Description: DiscountsController
 * @Author: Yang
 * @DateTime: 2023/3/5 20:48
 **/
@RestController
@CrossOrigin
@RequestMapping("/discounts")
public class DiscountsController {

    @Autowired
    private DiscountsService discountsService;

    @GetMapping("/page")
    public Result pageList(@RequestParam String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        Page<Discounts> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Discounts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Discounts::getExplains,name).orderByDesc(Discounts::getCreateTime);
        Page<Discounts> discountsPage = discountsService.page(page, queryWrapper);
        return Result.success(discountsPage);
    }

    @GetMapping("/getEndTime")
    public Result getEndTime(){
        LambdaQueryWrapper<Discounts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(Discounts::getBeginTime, DateTime.now())
                .ge(Discounts::getEndTime,DateTime.now())
                .eq(Discounts::getStatus,"1")
                .orderByDesc(Discounts::getCreateTime);
        List<Discounts> discountsList = discountsService.list(queryWrapper);
        Discounts discount = new Discounts();
        if (discountsList.size() != 0) {
            discount = discountsList.get(0);
        }
        return Result.success(discount);
    }

    @PostMapping("/addDiscounts")
    public Result addDiscounts(@RequestBody Discounts discounts){
        discounts.setCreateTime(LocalDateTime.now());
        discounts.setCreateUser(TokenUtils.getCurrentUser().getUsername());
        return Result.success(discountsService.save(discounts));
    }

    @PutMapping("/editDiscounts")
    public Result editDiscounts(@RequestBody Discounts discounts){
        discounts.setUpdateUser(TokenUtils.getCurrentUser().getUsername());
        discounts.setUpdateTime(LocalDateTime.now());
        return Result.success(discountsService.saveOrUpdate(discounts));
    }

    @GetMapping("/getDiscountById/{id}")
    public Result getDiscountById(@PathVariable("id") Integer id){
        return Result.success(discountsService.getById(id));
    }

    @DeleteMapping("/delDiscountById/{id}")
    public Result delDiscountById(@PathVariable("id") Integer id){
        return Result.success(discountsService.removeById(id));
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Integer>  data){
        return Result.success(discountsService.removeByIds(data));
    }

    //导出
    @AuthAccess
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Discounts> list = discountsService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("explains", "简要说明");
        writer.addHeaderAlias("proportion", "优惠程度");
        writer.addHeaderAlias("beginTime", "活动开始时间");
        writer.addHeaderAlias("endTime", "活动结束时间");
        writer.addHeaderAlias("createTime", "活动创建时间");
        writer.addHeaderAlias("createUser", "创建人");
        writer.addHeaderAlias("updateTime", "更新时间");
        writer.addHeaderAlias("updateUser", "更新人");
        writer.addHeaderAlias("status", "活动状态");
        writer.addHeaderAlias("description", "活动详细说明");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("活动信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

}
